﻿//-----------------------------------------------------------------------
// <copyright file="GoatObjectBuilder.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace GoatGen.Object
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using GoatGen.Token;

    /// <summary>
    /// Class that creates a Goat object from tokens.
    /// </summary>
    public class GoatObjectBuilder
    {
        #region Fields - Private

        /// <summary>
        /// List of tokens we have.
        /// </summary>
        private IList<GoatToken> tokens;

        /// <summary>
        /// Stak of tokens that we process.
        /// </summary>
        private Stack<GoatToken> tokenStack = new Stack<GoatToken>();

        #endregion

        #region Constructor

        /// <summary>
        /// Construct the builder.
        /// </summary>
        /// <param name="tokens">Tokens we will build with.</param>
        public GoatObjectBuilder(IList<GoatToken> tokens)
        {
            if (tokens == null)
            {
                throw new ArgumentNullException("tokens", "Tokens list must be non-null.");
            }

            this.tokens = tokens;

            foreach (GoatToken token in tokens.Reverse())
            {
                this.tokenStack.Push(token);
            }
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Build the object from tokens.
        /// </summary>
        /// <returns>Returns the build Goat object.</returns>
        public GoatObject Build()
        {
            try
            {
                // Get the global object begin.
                this.GetToken(GoatTokenType.StartObject);

                GoatObject res = this.BuildObject();

                // Get the end object token.
                this.GetToken(GoatTokenType.EndObject);

                return res;
            }
            catch (GoatException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new GoatException("Goat object build failed: " + e.ToString(), e);
            }
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Build an object from the tokens that we have.
        /// </summary>
        /// <returns>Returns the built Goat object.</returns>
        private GoatObject BuildObject()
        {
            GoatToken name = this.GetToken(GoatTokenType.PropertyName);

            GoatObject res = new GoatObject(name.Value);

            this.GetToken(GoatTokenType.StartObject);

            this.BuildObjectFields(res);

            this.GetToken(GoatTokenType.EndObject);

            return res;
        }

        /// <summary>
        /// Build the fields for the passed object.
        /// </summary>
        /// <param name="obj">Object to add fields to.</param>
        private void BuildObjectFields(GoatObject obj)
        {
            do 
            {
                GoatToken fieldName = this.GetToken(GoatTokenType.PropertyName);

                this.GetToken(GoatTokenType.StartObject);

                IDictionary<string, string> values = this.BuildFieldValues();
                GoatField field = GoatFieldFactory.Allocate(fieldName.Value, values);

                obj.AddField(field);
                
                this.GetToken(GoatTokenType.EndObject);
            }
            while (this.PeekToken(GoatTokenType.PropertyName));
        }

        /// <summary>
        /// Build the values that make up a field's definition.
        /// 
        /// For example, in this field:
        /// 
        /// "Size" :
        /// {
        ///     "type" : "Size2D",
        ///     "min" : "0.5 0.5",
        ///     "max" : "1024 1024",
        /// },
        /// 
        /// This function will return a dictionary with "type", "min" and "max" in it.
        /// </summary>
        /// <returns>Returns a key value dictionar of values.</returns>
        private IDictionary<string, string> BuildFieldValues()
        {
            IDictionary<string, string> res = new Dictionary<string, string>();

            do
            {
                GoatToken key = this.GetToken(GoatTokenType.PropertyName);
                GoatToken value = this.GetToken(GoatTokenType.Value);

                if (string.IsNullOrEmpty(key.Value))
                {
                    throw new ArgumentNullException("key", "Key must be non-null.");
                }

                res[key.Value] = value.Value;
            }
            while (this.PeekToken(GoatTokenType.PropertyName));

            return res;
        }

        /// <summary>
        /// Get a token off the top of the stack and ensure it is of the passed type.
        /// </summary>
        /// <param name="type">Type of token we want.</param>
        /// <returns>Returns the token on the top of the stack if it matches the passed type.</returns>
        private GoatToken GetToken(GoatTokenType type)
        {
            if (this.tokenStack.Count == 0)
            {
                throw new GoatException("Token stack is empty!");
            }

            GoatToken token = this.tokenStack.Pop();

            if (token.Type != type)
            {
                throw new GoatException(string.Format("Token type mismatch. Expected {0} and got {1}", type.ToString(), token.Type.ToString()));
            }

            return token;
        }

        /// <summary>
        /// Peek at the token that is on the top of the stack and test to
        /// see if it is of the passed type.
        /// </summary>
        /// <param name="type">Type to check for.</param>
        /// <returns>Returns true if the token on the top of the stack is the same as the passed type.</returns>
        private bool PeekToken(GoatTokenType type)
        {
            GoatToken token = this.tokenStack.Peek();

            return token.Type == type;
        }

        #endregion
    }
}